// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/shopspring/decimal"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/form"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"
	"time"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sSysAuctionProductMapper struct{}

func NewSysAuctionProductMapper() *sSysAuctionProductMapper {
	return &sSysAuctionProductMapper{}
}

func init() {
	service.RegisterSysAuctionProductMapper(NewSysAuctionProductMapper())
}

// Model 拍品管理ORM模型
func (s *sSysAuctionProductMapper) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.AuctionProductMapper.Ctx(ctx), option...)
}

// List 获取拍品管理列表
func (s *sSysAuctionProductMapper) List(ctx context.Context, in *sysin.AuctionProductMapperListInp) (list []*sysin.AuctionProductMapperListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.AuctionProductMapper.Table(), sysin.AuctionProductMapperListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionProductMapperListModel{}, &dao.Auction, "auction"))
	//mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionProductMapperListModel{}, &dao.Product, "product"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Auction.Table(), dao.AuctionProductMapper.Columns().AuctionId, "=", dao.Auction.Columns().Id)
	//mod = mod.LeftJoinOnFields(dao.Product.Table(), dao.AuctionProductMapper.Columns().ProductId, "=", dao.Product.Columns().Id)

	// 查询每周运行时间
	//if !in.Weekday.IsNil() {
	if len(in.Weekday) > 0 {
		mod = mod.Where("JSON_CONTAINS("+dao.AuctionProductMapper.Columns().Weekday+",JSON_ARRAY(?))", in.Weekday)
	}

	// 查询活动名称
	if in.AuctionId != 0 {
		mod = mod.Where(dao.AuctionProductMapper.Columns().AuctionId, in.AuctionId)
	}

	// 查询商品名称
	if in.ProductId != 0 {
		mod = mod.Where(dao.AuctionProductMapper.Columns().ProductId, in.ProductId)
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.AuctionProductMapper.Table() + "." + dao.AuctionProductMapper.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取拍品管理列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出拍品管理
func (s *sSysAuctionProductMapper) Export(ctx context.Context, in *sysin.AuctionProductMapperListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(sysin.AuctionProductMapperExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出拍品管理-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []sysin.AuctionProductMapperExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增拍品管理
func (s *sSysAuctionProductMapper) Edit(ctx context.Context, in *sysin.AuctionProductMapperEditInp) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		in.Status = consts.AuctionStatusEnd // 默认的状态为结束，便于定时任务
		// 修改
		if in.Id > 0 {
			if _, err = s.Model(ctx).
				Fields(sysin.AuctionProductMapperUpdateFields{}).
				WherePri(in.Id).Data(in).Update(); err != nil {
				err = gerror.Wrap(err, "修改拍品管理失败，请稍后重试！")
			}
			return
		}

		// 新增
		if _, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(sysin.AuctionProductMapperInsertFields{}).
			Data(in).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "新增拍品管理失败，请稍后重试！")
		}
		return
	})
}

// Delete 删除拍品管理
func (s *sSysAuctionProductMapper) Delete(ctx context.Context, in *sysin.AuctionProductMapperDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除拍品管理失败，请稍后重试！")
		return
	}
	return
}

// View 获取拍品管理指定信息
func (s *sSysAuctionProductMapper) View(ctx context.Context, in *sysin.AuctionProductMapperViewInp) (res *sysin.AuctionProductMapperViewModel, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.AuctionProductMapper.Table(), sysin.AuctionProductMapperViewModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, sysin.AuctionProductMapperViewModel{}, &dao.Auction, "auction"))

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Auction.Table(), dao.AuctionProductMapper.Columns().AuctionId, "=", dao.Auction.Columns().Id)

	if err = mod.WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取拍品管理信息，请稍后重试！")
		return
	}
	return
}

// WorkingNow 立即上架场次
func (this *sSysAuctionProductMapper) WorkingNow(ctx context.Context, in *sysin.AuctionLogViewInp) (res *sysin.AuctionProductMapperViewModel, err error) {
	if err = this.Model(ctx).WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取竞拍记录信息，请稍后重试！")
		return
	}
	if res.Status != consts.AuctionStatusEnd {
		err = gerror.New("只有已结束的竞拍记录才能开始")
		return
	}
	var auction entity.Auction
	if err = service.SysAuction().Model(ctx).WherePri(res.AuctionId).Scan(&auction); err != nil {
		return
	}
	if auction.StartDate.Before(gtime.Now()) || auction.EndDate.After(gtime.Now()) {
		err = gerror.New("竞拍活动未开始或已结束")
		return
	}
	var log entity.AuctionLog
	if err = service.SysAuctionLog().Model(ctx).
		Where(dao.AuctionLog.Columns().MapperId, in.Id).
		Where(dao.AuctionLog.Columns().Date, gtime.Now().Format(time.DateOnly)).
		Scan(&log); err != nil {
		return
	}
	if log.Id > 0 {
		err = gerror.New("今日已存在场次")
		return
	}
	if err = service.SysAuctionLog().Edit(ctx, &sysin.AuctionLogEditInp{
		AuctionLog: entity.AuctionLog{
			AuctionId:            auction.Id,
			MapperId:             res.Id,
			ProductId:            uint64(res.ProductId),
			FinalPrice:           decimal.NewFromInt(0).InexactFloat64(),
			Date:                 gtime.Now(),
			StartTime:            res.StartTime,
			EndTime:              res.EndTime,
			NumberOfParticipants: 0,
		},
	}); err != nil {
		return
	}

	return
}

// ActiveAuctionMapper 活跃的竞拍活动
func (this *sSysAuctionProductMapper) ActiveAuctionMapper(ctx context.Context, in *sysin.AuctionProductMapperActiveInp) (list []*sysin.AuctionProductMapperActiveModel, total int, err error) {
	mod := this.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.AuctionProductMapper.Table(), sysin.AuctionProductMapperListModel{})

	// 查询活跃的竞拍活动
	if in.ListType == consts.AuctionListTypeWorking {
		mod = mod.Where(dao.AuctionProductMapper.Columns().Status, consts.AuctionStatusWorking)
	}

	// 查询今日活动
	if in.ListType == consts.AuctionListTypeToday {
		var (
			auctionList []entity.Auction
			auctionIds  []uint64
		)
		if err = service.SysAuction().Model(ctx).
			Where(dao.Auction.Columns().Enabled, true).
			WhereLTE(dao.Auction.Columns().StartDate, gtime.Now().Layout(time.DateOnly)).
			WhereGTE(dao.Auction.Columns().EndDate, gtime.Now().Layout(time.DateOnly)).
			Scan(&auctionList); err != nil {
			err = gerror.Wrap(err, "获取活跃的竞拍活动失败，请稍后重试！")
			return
		}
		for _, auction := range auctionList {
			auctionIds = append(auctionIds, auction.Id)
		}

		mod = mod.WhereIn(dao.AuctionProductMapper.Columns().AuctionId, auctionIds)
		mod = mod.Where("JSON_CONTAINS(`weekday`, ?)", gconv.String(int(gtime.Now().Weekday())))
	}

	if err = mod.ScanAndCount(&list, &total, false); err != nil {
		err = gerror.Wrap(err, "获取活跃的竞拍活动失败，请稍后重试！")
		return
	}
	for i, model := range list {
		var logList []*sysin.AuctionLogListModel

		logList, _, _ = service.SysAuctionLog().List(ctx, &sysin.AuctionLogListInp{
			AuctionId: model.AuctionId,
			Date:      gtime.Now(),
		})
		if len(logList) > 0 {
			list[i].AuctionLogList = logList
		}
	}

	return
}
